/* eslint-disable no-underscore-dangle */
/**
 * 普通的确认弹窗传四个参数-> {
 *    title , // 标题
      contentBegin, // eg: 确认要删除伸缩组
      nameId, //  eg: xxy-test-as-1(2476152446914568266) 
      contentEnd:   // 后面拼接字  默认 吗？
      type: "warngin" 或者 “question”  默认"question" 控制图表类型
      subContent, // eg: 下面的灰色小字 停用伸缩组后，自动的扩缩容不再进行：包括告警伸缩、匹配期望实例数的伸缩
    } 
    如果要自定义内容 可以传content字段
 */
// 示例
// hcpConfirm({
//   title:"删除伸缩组",
//   contentBegin:"确定要删除伸缩组",
//   nameId:`${record.instanceName}(${record.instanceId})`,
//   onFinish:()=>request({
//     ...hcpresource.deleteASGroup(record.instanceId),
//     // headers: { 'instanceId': row.instanceId, 'instanceName': row.instanceName}
//   }),
// })
// .then((e)=>{  // 确定回调
//   message.success(`删除成功`);
//   getTableData()
// })
// .catch((er)=>{console.log(er)}) // 取消回调

import React, { useState, useRef,useLayoutEffect } from "react";
import { Button, Modal, message, Form } from "antd";
import ReactDOM from 'react-dom';
import './index.less';

let _reject = null;
let _resolve = null;
let _promise = null;
const iconfont = {
  'warning':['red','warning'],
  'question':['yellow','question']
}

const HcpConfirmModal = (props) => {
  const {
      cancelText, 
      okText,
      destroy,
      title ,
      contentBegin,
      nameId,
      subContent,
      content,
      onFinish,
      contentEnd,
      type='question', 
      ...prop} = props;
  let _content = (
    <>
      <div className="main-content">
        <span className={`iconfont iconfont-${iconfont[type][0]} icon-confirm-${iconfont[type][1]}`} />
        <span className="main-content-info">{contentBegin || '-'}
          <span className="gray">{nameId || '-'}</span> { contentEnd || '吗?'}</span>
      </div>
      <div className="sub-content gray">{subContent}</div>
    </>
  )
  const [visible,setVisible] = useState(true);
  const [loading,setLoading] = useState(false);

    useLayoutEffect(()=>{
      if(visible === true){
        _promise = new Promise((resolve,reject)=>{
          _reject = reject;
          _resolve = resolve;
      });
      }
    },[visible]);

    async function onOk(){
      try{
        let res = null;
        if(onFinish){
        setLoading(true);
        res = await onFinish();
        }
        if(res){
          _resolve(res);
        }
      }catch(err){
        _reject(err);
      }
      setVisible(false);
      setLoading(false);
      destroy();
    }

    function onCancel(){
        setVisible(false);
        _reject('111');
        destroy();
    }

  return (
    <Modal
      {...prop}
      prefixCls="hcp-modal"
      className="hcp-tip-modal hcp-modal-sm"
      title={title}
      visible={visible}
      onCancel={onCancel}
      footer={null}
      destroyOnClose
      maskClosable={false}
    >
      <div className="hcp-tip-modal-body">
        {content || _content}
      </div>
      <div className="hcp-tip-modal-footer">
        {cancelText ? <Button prefixCls="hcp-btn" onClick={onCancel}>{cancelText || "取消"}</Button> : ""}
        <Button style={{ marginLeft: 15, }} prefixCls="hcp-btn" loading={loading} type="primary" onClick={onOk} >{okText || '确定'}</Button>
      </div>
    </Modal>
  );
};


export default function hcpConfirm(config={ title:"确认框", okText : "确定", cancelText : "取消", content:"ooo" }){
  let currentConfig = { ...config, destroy, visible: true };
  const div = document.createElement('div');

  function destroy() {
    const unmountResult = ReactDOM.unmountComponentAtNode(div);
    if (unmountResult && div.parentNode) {
      div.parentNode.removeChild(div);
    }
  }

  function render({ okText = "确定", cancelText = "取消", ...props }) {
    // setTimeout(() => {
      ReactDOM.render(
        <HcpConfirmModal
          {...props}
          okText={okText}
          cancelText={cancelText}
        />,
        div,
      );
    // });
  }

  render(currentConfig);

  return _promise;
}
